package com.gtallinone.client;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.omg.CORBA.DATA_CONVERSION;


import com.gtallinone.client.GreetingService;
import com.gtallinone.client.GreetingServiceAsync;
import com.gtallinone.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HorizontalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class GTAllInOne implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	public static GreetingServiceAsync rpc;
	
	public GTAllInOne()
	{
		rpc = (GreetingServiceAsync) GWT.create(GreetingService.class);
        ServiceDefTarget target = (ServiceDefTarget) rpc;
        
        // The path 'MySQLConnection' is determined in ./public/LoginScreen.gwt.xml
        // This path directs Tomcat to listen for this context on the server side, 
        // thus intercepting the rpc requests.
        String moduleRelativeURL = GWT.getModuleBaseURL() + "GreetingServiceImpl";
        //System.out.println("Module Relative URL is -> "+moduleRelativeURL);
        target.setServiceEntryPoint(moduleRelativeURL);
	}
	
	/*********temp Create Account**********/
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Label errorLabel = new Label();

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		final RootPanel rootPanel = RootPanel.get("nameFieldContainer");
		RootPanel.get("errorLabelContainer").add(errorLabel);
		rootPanel.setSize("80%","80%");
		
		//Log in panel
		final VerticalPanel verticalPanel = new VerticalPanel();
		verticalPanel.addStyleName("logInPanel");
		verticalPanel.setSize("100%", "100%");
		verticalPanel.setBorderWidth(5);
		rootPanel.add(verticalPanel);
		
		Label title = new Label("GT All In One");
		title.addStyleName("appTitle");
		verticalPanel.add(title);
				
		Label lblLogIn = new Label("Log In:");
		verticalPanel.add(lblLogIn);
				
		Grid grid = new Grid(2, 2);
		verticalPanel.add(grid);
		grid.setSize("158px", "53px");
				
		Label lblUserName = new Label("User Name ");
		grid.setWidget(0, 0, lblUserName);
		lblUserName.setWidth("76px");
		final TextBox nameField = new TextBox();
		grid.setWidget(0, 1, nameField);
		String userName = nameField.getText();
		nameField.setFocus(true);
		Label lblPassword = new Label("Password");
		grid.setWidget(1, 0, lblPassword);
		final PasswordTextBox passField = new PasswordTextBox();
		grid.setWidget(1, 1, passField);
		String password = passField.getText();
		nameField.selectAll();
		
		
		HorizontalPanel horizontalPanel = new HorizontalPanel();
		verticalPanel.add(horizontalPanel);
				
		final Button sendButton = new Button("Log In");
		sendButton.setSize("100%", "100%");
		horizontalPanel.add(sendButton);
		sendButton.addStyleName("sendButton");
		final Button btnCreateAccount = new Button("Create Account");
		btnCreateAccount.setSize("100%", "100%");
		horizontalPanel.add(btnCreateAccount);

		
		// Create Account Dialog Box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Create New Account");
		dialogBox.setAnimationEnabled(true);
		final Button createAccountBtn = new Button("Create Account");
		final Button closeButton = new Button("Canel");
		createAccountBtn.getElement().setId("closeButton");
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final TextBox newEmail = new TextBox();
		final TextBox newUsername = new TextBox();
		final PasswordTextBox newPassword = new PasswordTextBox();
		final PasswordTextBox confirmPassword = new PasswordTextBox();

		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");

		dialogVPanel.add(new HTML("<b>Your E-mail Address:</b>"));
		dialogVPanel.add(newEmail);
		dialogVPanel.add(new HTML("<b>Your New Username:</b>"));
		dialogVPanel.add(newUsername);
		//dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Your New Password:</b>"));
		dialogVPanel.add(newPassword);
		//dialogVPanel.add(serverResponseLabel);
		dialogVPanel.add(new HTML("<br><b>Confirm Your Password:</b>"));
		dialogVPanel.add(confirmPassword);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_CENTER);
		HorizontalPanel hp1 = new HorizontalPanel();
		hp1.add(createAccountBtn);
		hp1.add(closeButton);
		dialogVPanel.add(hp1);
		dialogBox.setWidget(dialogVPanel);

		createAccountBtn.addClickHandler(new ClickHandler(){
			public void onClick(ClickEvent event){
				dialogBox.hide();
				btnCreateAccount.setEnabled(true);
				btnCreateAccount.setFocus(true);
				
				final DialogBox dialogBox2 = new DialogBox();
				VerticalPanel vp1 = new VerticalPanel();
				final Button close = new Button("Close");
				dialogBox2.setText("Create New Account");
				vp1.add(new HTML("<b>Your new account was successfully created!</b>"));
				vp1.add(close);
				dialogBox2.setWidget(vp1);
				dialogBox2.center();
				
				close.addClickHandler(new ClickHandler() {
					public void onClick(ClickEvent event) {
						dialogBox2.hide();
					}
				});
			}
		});
		
		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				btnCreateAccount.setEnabled(true);
				btnCreateAccount.setFocus(true);
			}
		});

		
		// Login Handler for the logInButton and passField
		class LogInHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				String username = nameField.getText();
				String password = passField.getText();
				/*
				try{
					System.out.println("Failed1");

					Class.forName("com.mysql.jdbc.Driver");
					System.out.println("Failed2");

				}catch(ClassNotFoundException e1){
					System.out.println("Failed3");
					System.out.println(e1.getMessage());
					return;
				}*/
				
				
				if(password.compareTo("password") == 0){
					rootPanel.setSize("100%", "100%");
					verticalPanel.removeFromParent();
					AppPanel ap = new AppPanel();
					ap.setSize("80%", "80%");
					rootPanel.add(ap);
				}else{
					System.out.println("Password was "+ password +" and login was failed");
				}
			}

			/**
			 * Fired when the user types in the passField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				
				//get a password
				AsyncCallback<String> callback_t = new AuthenticationHandler1<String>();//////////TEST//////////////////////////////////////////////////////////////
				System.out.println("done here");
				rpc.getPassword(nameField.getText(), callback_t);
				System.out.println("done here2");
				
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					String password = passField.getText();
					if(password.compareTo("password") == 0){
						rootPanel.setSize("100%", "100%");
						verticalPanel.removeFromParent();
						AppPanel ap = new AppPanel();
						ap.setSize("80%", "80%");
						rootPanel.add(ap);
					}else{
						System.out.println("Password was "+ password +" and login was failed");
					}
				}
			}
		}
		
		//add handler to button and field
		LogInHandler logInHandler = new LogInHandler();
		passField.addKeyUpHandler(logInHandler);
		sendButton.addClickHandler(logInHandler);

		
		
		
		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler, KeyUpHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				createAccountPage();
			}

			/**
			 * Fired when the user types in the nameField.
			 */
			public void onKeyUp(KeyUpEvent event) {
				if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
					createAccountPage();
				}
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void createAccountPage() {
				btnCreateAccount.setEnabled(false);

				
				// First, we validate the input.
				
				errorLabel.setText("");
				String textToServer = nameField.getText();


				// Then, we send the input to the server.
				btnCreateAccount.setEnabled(false);
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.greetServer(textToServer,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox.setText("Create New Account");
								serverResponseLabel.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Create New Account");
								serverResponseLabel.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								closeButton.setFocus(true);
							}
						});
			
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		btnCreateAccount.addClickHandler(handler);
	}
	
	
	/*private class AuthenticationHandler1<T> implements AsyncCallback<ArrayList> {//Handler for Attribute Names for View Listbox3
        public void onFailure(Throwable ex) {
       RootPanel.get().add(new HTML("RPC call failed. :-("));
           }
		public void onSuccess(ArrayList result) {
        	RootPanel.get().add(new HTML("RPC call success  : -)"));
        	attributeNames = result;
        	attribute.clear();
        	for(int i = 0; i < attributeNames.size(); i++){
        		attribute.addItem((String) attributeNames.get(i));
    		}
        }

   }*/
	
	private class AuthenticationHandler1<T> implements AsyncCallback<String> {//Handler for Attribute Names for View Listbox3
        public void onFailure(Throwable ex) {
       RootPanel.get().add(new HTML("RPC call failed. :-("));
           }
		public void onSuccess(String result) {
        	RootPanel.get().add(new HTML("RPC call success  : -)"));
        	System.out.println(result);

        }

   }
	
}
